package com.piaoniu.open.api.domain.order.dto;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by evan on 2017/10/15.
 */
@Data
public class OrderIdCardDTO {
    String name;
    String idCard;
    int buyCount; //一张身份证买了几张票

    public static boolean isVaild(List<OrderIdCardDTO> orderIdCards,int needCount){
        if (orderIdCards == null)
            return false;

        if (orderIdCards.stream().anyMatch(e-> StringUtils.isBlank(e.getIdCard()) || StringUtils.isBlank(e.getName())))
            return false;

        if (orderIdCards.size() != needCount)
            return false;

        List<String> idCards = orderIdCards.stream().filter(e-> StringUtils.isNotBlank(e.getIdCard()))
            .map(e->e.getIdCard().toUpperCase()).distinct().collect(Collectors.toList());

        if (idCards.size() != orderIdCards.size())
            return false;

        return orderIdCards.stream().allMatch(e->{
            Matcher m = idCardPattern.matcher(e.getIdCard());
            return m.matches();
        });
    }

    private static final String IDCARD="((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)[0-9]{4})" +
        "(([1|2][0-9]{3}[0|1][0-9][0-3][0-9][0-9]{3}" +
        "[Xx0-9])|([0-9]{2}[0|1][0-9][0-3][0-9][0-9]{3}))";

    private static Pattern idCardPattern = Pattern.compile(IDCARD);
}
